package dhome;

import java.io.BufferedReader;
import java.io.File;
import java.io.InputStreamReader;
import java.net.InetAddress;
import java.nio.charset.Charset;
import java.util.HashMap;

public class Host {			
	protected static Runtime run = Runtime.getRuntime();
	private static Charset _charset=Charset.defaultCharset();
	
	/**
	 * 获得系统变量的值 Usage： getSystemInfo("hostname") getSystemInfo("ip")
	 * 返回LocalHost网卡ipv4地址.
	 * 
	 * @param type
	 *            the type
	 * @return the system info
	 */
	public static String getSystemInfo(String type) {
		try {
			if (System.getProperty(type) != null)
				return System.getProperty(type);
			if (type.equalsIgnoreCase("ip")) {
				InetAddress i = InetAddress.getLocalHost();
				if (i.getHostName() != null && i.getHostName().length() > 0)
					return i.getHostName();
				return i.getHostAddress();
			}

		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}
	
	/**
	 * 执行一个命令，返回原始结果.
	 * 不会处理switchTo函数的传入目录
	 * @param cmd
	 *            the cmd
	 * @return the string
	 */
	public static String exec0(String cmd) {
		String line = "";
		try {
			Process pro = run.exec(new String[]{"sh","-c",cmd});
			BufferedReader bri = new BufferedReader(new InputStreamReader(
					pro.getInputStream(), _charset));

			String tmp = null;
			while ((tmp = bri.readLine()) != null){
				line += tmp.trim() + "\n";
			}
			bri.close();
			pro.waitFor();
		
			if (line == null || line.trim().length() == 0)
				System.out.println("exec no return "+cmd);
			
		} catch (Exception e) {
			e.printStackTrace();
		}
		return line;
	}

	/**
	 * 执行 && 返回
	 * 不会处理switchTo函数的传入目录
	 * @param cmd
	 */
	public static void exec0_wait(String cmd) {
		try {
			Process pro = run.exec(new String[]{"sh","-c",cmd});
			final Process fpro = pro;
			new Thread() {
				@Override
				public void run() {
					try {
						fpro.waitFor();
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
				}
			};
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

//	public String execToString(String command) {	   
//	    CommandLine commandline = CommandLine.parse(command);
//	    
//	    try {			
//			exec.execute(commandline);
//		} catch (Exception e) {			
//			e.printStackTrace();
//		}
//	    return(outputStream.toString()); 
//	}

	/**
	 * 执行 && 等待结果
	 * 不会处理switchTo函数的传入目录
	 * 
	 * @param cmd
	 */
	public void exec0_without_return(String cmd) {
		try {
			Process pro = run.exec(cmd);
			pro.waitFor();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	
	/**
	 * host的字符集，默认为charset
	 * 
	 * @param charset
	 * @see Expect#charset
	 */
	public static void set_charset(String charset) {
		_charset = Charset.forName(charset);
	}

}